<template>
	<view>
		<view :class="['message-item', item.fromId===meId ? 'right' : '']" v-for="item in messageList">
			<image v-if="item.fromId !== meId" class="message-avatar" :src="toInfo.avatar" mode=""></image>
			<view v-if="typeof(item.message)=='string'" class="message-con">
				<rich-text :nodes="item.message"></rich-text>
			</view>
			<up-icon v-else name="volume" @click="handleAudio(item.message)" size="26"></up-icon>
			<image v-if="item.fromId === meId" class="message-avatar" :src="myInfo.avatar" mode=""></image>
		</view>
		<view class="footer">
			<view class="send-model">
				<up-input
				    placeholder="请输入内容"
				    border="surround"
				    v-model="messageValue"
				  ></up-input>
				  <button size="mini" @click="doSend">发送</button>
				  <up-icon name="photo" @click="selectImg" size="26"></up-icon>
				  <up-icon name="chat" @click="handleIcon" size="26"></up-icon>
				  <up-icon name="mic" size="26" @longpress="startRecorder" @touchend="stopRecorder"></up-icon>
			</view>
			<view v-if="showIcon" class="icon-list">
				<image @click="selectIcon(item)" class="icon-item" :src="item.url" v-for="item in iconList" mode=""></image>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import {onLoad} from '@dcloudio/uni-app'
import io from '@hyoga/uni-socket.io';
	const meId = ref('')
	const toId = ref('')
	const toInfo = ref({})
	const myInfo = ref({})
	const messageValue = ref('')
	const showIcon = ref(false)
	// 创建全局唯一的录音管理器
	// #ifdef MP-WEIXIN
	const recorderManager = uni.getRecorderManager()
	const innerAudioContext = uni.createInnerAudioContext();
	recorderManager.onStop((res) => {
		console.log(res)
		const messageObj = {
			fromId: meId.value,
			toId: toId.value,
			message: {
				url: res.tempFilePath
			}
		}
		messageList.value.push(messageObj)
		socket.emit('sendMsg', messageObj)
	})
	// #endif
	const handleAudio = (audioMessage) => {
		innerAudioContext.src = audioMessage.url
		if(innerAudioContext.paused) {
			innerAudioContext.play()
		} else {
			innerAudioContext.pause()
		}
	}
	const startRecorder = () => {
		recorderManager.start()
	}
	const stopRecorder = () => {
		recorderManager.stop()
	}
	const iconList = ref([
		{url: '/static/icon/bs.png', code: '/bs'},
		{url: '/static/icon/cj.png', code: '/cj'},
		{url: '/static/icon/eye.png', code: '/eye'},
		{url: '/static/icon/sq.png', code: '/sq'},
		{url: '/static/icon/yg.png', code: '/yg'}
	])
	const personList = [
		{name: '李少斌', id:'bin', avatar: 'https://gips2.baidu.com/it/u=1651586290,17201034&fm=3028&app=3028&f=JPEG&fmt=auto&q=100&size=f600_800'},
		{name: '张学友', id:'zxy', avatar: 'http://gips1.baidu.com/it/u=3874647369,3220417986&fm=3028&app=3028&f=JPEG&fmt=auto?w=720&h=1280'},
	]
	let timer = null
	const doHeart = () => {
		timer && clearInterval(timer)
		timer = setInterval(() => {
			socket.emit('ping')
		}, 20000)
	}
	
	let socket;
	const linkSocket = () => {
		socket = io('ws://localhost:3000', {
			path: '/mysocket',
		  query: {
			  id: meId.value
		  },
		  transports: [ 'websocket', 'polling' ],
		  timeout: 5000,
		});
		socket.on('connect', () => {
			console.log('链接服务端成功')
			doHeart()
			socket.on('receiveMsg', info => {
				messageList.value.push(info)
			})
			socket.on('pang', () => {
				console.log('一次心跳检测完成')
			})
		})
	}
	onLoad(options => {
		// 从url里面获取参数并赋值给对应的变量
		meId.value = options.meId
		toId.value = options.toId
		getUserInfo()
		linkSocket()
	})
	const getUserInfo = () => {
		toInfo.value = personList.find(item => item.id===toId.value) || {}
		myInfo.value = personList.find(item => item.id === meId.value) || {}
	}
	const messageList = ref([
		{fromId: 'bin', toId: 'zxy', message: '你好'},
		{fromId: 'zxy', toId: 'bin', message: '你也好'}
	])
	const codeToImg = str => {
		let newStr = str
		iconList.value.forEach(item => {
			newStr = newStr.replaceAll(item.code, `<img width="50" height="50" src="${item.url}" />`)
		})
		return newStr
	}
	const doSend = () => {
		const messageObj = {
			fromId: meId.value,
			toId: toId.value,
			message: codeToImg(messageValue.value)
		}
		socket.emit('sendMsg', messageObj)
		messageList.value.push(messageObj)
		messageValue.value = ''
	}
	const selectImg = () => {
		uni.chooseImage({
			success(res) {
				console.log(res)
				const url = res.tempFilePaths[0]
				const messageObj = {
					fromId: meId.value,
					toId: toId.value,
					message: `<img width="150" src="${url}" />`
				}
				messageList.value.push(messageObj)
				socket.emit('sendMsg', messageObj)
			}
		})
	}
	const handleIcon = () => {
		showIcon.value = !showIcon.value
	}
	const selectIcon = icon => {
		messageValue.value += icon.code
	}
</script>

<style lang="scss" scoped>
	.message-item {
		display: flex;
		margin-bottom: 10rpx;
		.message-avatar{
			width: 80rpx;
			height: 80rpx;
		}
		.message-con{
			display: flex;
			background: #87c1ed;
			border-radius: 10rpx;
			padding: 10rpx;
			margin: 0 10rpx;
		}
		&.right{
			justify-content: flex-end;
		}
	}
	.footer{
		position: fixed;
		bottom: 0;
		width: 100vw;
		.send-model{
			display: flex;
		}
		.icon-list{
			display: flex;
			.icon-item{
				width: 60rpx;
				height: 60rpx;
			}
		}
	}
</style>
